package com.cf.base.sp.engine.impl;

import android.content.Context;
import android.content.SharedPreferences;

import com.cf.base.sp.annotation.Level;
import com.cf.base.sp.engine.Storage;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangji
 */
public class SharedPreferencesStorageImpl implements Storage {

    private final String mFileName;
    private final Context mContext;
    private Map<Level, SharedPreferences> preferencesMap = new HashMap<>();
    private final Object lock = new Object();

    private SharedPreferences getSharePreferences(Level level) {
        SharedPreferences sp = preferencesMap.get(level);
        if (sp == null) {
            synchronized (lock) {
                SharedPreferences preferences = mContext.getApplicationContext()
                        .getSharedPreferences(mFileName + "_" + level.name(), Context.MODE_PRIVATE);
                preferencesMap.put(level, preferences);
                sp = preferences;
            }
        }
        return preferencesMap.get(level);
    }

    public SharedPreferencesStorageImpl(Context context, String fileName) {
        this.mFileName = fileName;
        this.mContext = context.getApplicationContext();
    }

    private SharedPreferences.Editor getEditor(Level level) {
        return getSharePreferences(level).edit();
    }

    @Override
    public boolean put(String key, String t, Level level) {
        getEditor(level).putString(key, t).apply();
        return true;
    }

    @Override
    public String get(String key, Level level) {
        return getSharePreferences(level).getString(key, null);
    }

    @Override
    public int count(Level level) {
        return getSharePreferences(level).getAll().size();
    }

    @Override
    public boolean contains(String key, Level level) {
        return getSharePreferences(level).contains(key);
    }

    @Override
    public void delete(String key, Level level) {
        getEditor(level).remove(key);
    }

    @Override
    public void clear(Level level) {
        getEditor(level).clear();
    }
}
